package com.lgj.web.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lgj.core.LoginUser;
import com.lgj.exception.BusinessException;
import com.lgj.web.sys.common.SpringUtil;
import com.lgj.web.sys.mapper.SysUserMapper;
import com.lgj.web.sys.mapper.SysUserRoleRelationMapper;
import com.lgj.web.sys.model.*;
import com.lgj.web.sys.service.SysUserCacheService;
import com.lgj.web.sys.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 后台用户管理Service实现类
 * Created by macro on 2018/4/26.
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SysUserRoleRelationMapper sysUserRoleRelationMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser getAdminByUsername(String username) {
        //先从缓存中获取数据
        SysUser admin = getCacheService().getUser(username);
        if (admin != null) return admin;
        //缓存中没有从数据库中获取
        SysUser user = sysUserMapper.selectByUsername(username);
        if (user != null){
            getCacheService().setUser(user);
        }
        return user;
    }

    @Override
    public SysUser register(SysUserParam sysUserParam) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserParam, sysUser);
        sysUser.setCreateTime(new Date());
        sysUser.setStatus(1);
        //查询是否有相同用户名的用户
        SysUser user = sysUserMapper.selectByUsername(sysUserParam.getUsername());
        if (user!= null){
            return null;
        }
        //将密码进行加密操作
        String encodePassword = passwordEncoder.encode(sysUser.getPassword());
        sysUser.setPassword(encodePassword);
        sysUserMapper.insert(sysUser);
        return sysUser;
    }

    @Override
    public String login(String username, String password) {
        String token = null;
//        //密码需要客户端加密后传递
//        try {
//            UserDetails userDetails = loadUserByUsername(username);
//            if(!passwordEncoder.matches(password,userDetails.getPassword())){
//                throw new BusinessException("密码不正确");
//            }
//            if(!userDetails.isEnabled()){
//                throw new BusinessException("帐号已被禁用");
//            }
//            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
//            SecurityContextHolder.getContext().setAuthentication(authentication);
//        } catch (AuthenticationException e) {
//            LOGGER.warn("登录异常:{}", e.getMessage());
//        }
        return token;
    }


    @Override
    public String refreshToken(String oldToken) {
       // return jwtTokenUtil.refreshHeadToken(oldToken);
        return null;
    }

    @Override
    public SysUser getItem(Long id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo list(String keyword, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo page = new PageInfo( sysUserMapper.selectPageList(keyword));
        return page;
    }

    @Override
    public int update(Long id, SysUser admin) {
        admin.setId(id);
        SysUser rawAdmin = sysUserMapper.selectByPrimaryKey(id);
        if(rawAdmin.getPassword().equals(admin.getPassword())){
            //与原加密密码相同的不需要修改
            admin.setPassword(null);
        }else{
            //与原加密密码不同的需要加密修改
            if(StringUtils.isEmpty(admin.getPassword())){
                admin.setPassword(null);
            }else{
                admin.setPassword(passwordEncoder.encode(admin.getPassword()));
            }
        }
        int count = sysUserMapper.updateByPrimaryKeySelective(admin);
        getCacheService().delUser(id);
        return count;
    }

    @Override
    public int delete(Long id) {
        getCacheService().delUser(id);
        int count = sysUserMapper.deleteByPrimaryKey(id);
        getCacheService().delResourceList(id);
        return count;
    }

    @Override
    public int updateRole(Long userId, List<Long> roleIds) {
        int count = roleIds == null ? 0 : roleIds.size();
        //先删除原来的关系
        sysUserRoleRelationMapper.deleteByUserId(userId);
        //建立新关系
        if (!CollectionUtils.isEmpty(roleIds)) {
            List<SysUserRoleRelation> list = new ArrayList<>();
            for (Long roleId : roleIds) {
                SysUserRoleRelation roleRelation = new SysUserRoleRelation();
                roleRelation.setuserId(userId);
                roleRelation.setRoleId(roleId);
                list.add(roleRelation);
            }
            sysUserMapper.insertList(list);
        }
        getCacheService().delResourceList(userId);
        return count;
    }

    @Override
    public List<SysRole> getRoleList(Long userId) {
        return sysUserMapper.getRoleList(userId);
    }

    @Override
    public List<SysResource> getResourceList(Long userId) {
        //先从缓存中获取数据
        List<SysResource> resourceList = getCacheService().getResourceList(userId);
        if(!CollectionUtils.isEmpty(resourceList)){
            return  resourceList;
        }
        //缓存中没有从数据库中获取
        resourceList = sysUserMapper.getResourceList(userId);
        if(!CollectionUtils.isEmpty(resourceList)){
            //将数据库中的数据存入缓存中
            getCacheService().setResourceList(userId,resourceList);
        }
        return resourceList;
    }

    @Override
    public int updatePassword(UpdateUserPasswordParam param) {
        if(StringUtils.isEmpty(param.getUsername())
                ||StringUtils.isEmpty(param.getOldPassword())
                ||StringUtils.isEmpty(param.getNewPassword())){
            return -1;
        }
        SysUser SysUser = sysUserMapper.selectByUsername(param.getUsername());
        if(SysUser == null){
            return -2;
        }
        if(!passwordEncoder.matches(param.getOldPassword(),SysUser.getPassword())){
            return -3;
        }
        SysUser.setPassword(passwordEncoder.encode(param.getNewPassword()));
        sysUserMapper.updateByPrimaryKey(SysUser);
        getCacheService().delUser(SysUser.getId());
        return 1;
    }


    @Override
    public SysUserCacheService getCacheService() {
        return SpringUtil.getBean(SysUserCacheService.class);
    }

    @Override
    public LoginUser getUserByUserName(String userName) {
        return sysUserMapper.getUserByUserName(userName);
    }
}
